<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!-- Content Header (Page header) -->
<section class="content-header no-margin">
	<h1 class="text-center">
		<spring:message code="admin.message.mailbox" />
	</h1>
</section>

<!-- Main content -->
<section class="content">
	<!-- MAILBOX BEGIN -->
	<div class="mailbox row">
		<div class="col-xs-12">
			<div class="box box-solid">
				<div class="box-body">
					<div class="row">
						<div class="col-md-3 col-sm-4">
							<!-- BOXES are complex enough to move the .box-header around.
                                                 This is an example of having the box header within the box body -->
							<div class="box-header">
								<i class="fa fa-inbox"></i>
								<h3 class="box-title">
									<c:choose>
										<c:when test="${param.mode=='INBOX'}">
											<spring:message code="admin.message.inbox" />
										</c:when>
										<c:when test="${param.mode=='SENT'}">
											<spring:message code="admin.message.sent" />
										</c:when>
										<c:when test="${param.mode=='TRASH'}">
											<spring:message code="admin.message.trash" />
										</c:when>
									</c:choose>
								</h3>
							</div>
							<!-- compose message btn -->
							<a class="btn btn-block btn-primary" data-toggle="modal"
								data-target="#compose-modal"><i class="fa fa-pencil"></i> <spring:message
									code="admin.message.compose" /></a>
							<!-- Navigation - folders-->
							<div style="margin-top: 15px;">
								<ul class="nav nav-pills nav-stacked">
									<li class="header"><spring:message
											code="admin.message.folders" /></li>
									<li <c:if test="${param.mode=='INBOX'}">class="active" </c:if>><a
										href="getMailBox.html?mode=INBOX"><i class="fa fa-inbox"></i>
											<spring:message code="admin.message.inbox" /> (<span
											id="newMail"></span>)</a></li>
									<!-- <li><a href="#"><i class="fa fa-pencil-square-o"></i> Drafts</a></li> -->
									<li <c:if test="${param.mode=='SENT'}">class="active" </c:if>><a
										href="getMailBox.html?mode=SENT"><i
											class="fa fa-mail-forward"></i> <spring:message
												code="admin.message.sent" /></a></li>
									<!-- <li><a href="#"><i class="fa fa-star"></i> Starred</a></li> -->
									<li <c:if test="${param.mode=='TRASH'}">class="active" </c:if>><a
										href="getMailBox.html?mode=TRASH"><i class="fa fa-trash-o"></i>
											<spring:message code="admin.message.trash" /></a></li>
								</ul>
							</div>
						</div>
						<!-- /.col (LEFT) -->
						<div class="col-md-9 col-sm-8">
							<div class="row pad">
								<div class="col-sm-6">
									<label style="margin-right: 10px;"> <input
										type="checkbox" id="check-all" />
									</label>
									<!-- Action button -->
									<div class="btn-group">
										<button type="button"
											class="btn btn-default btn-sm btn-flat dropdown-toggle"
											data-toggle="dropdown">
											<spring:message code="admin.message.action" />
											<span class="caret"></span>
										</button>
										<ul class="dropdown-menu" role="menu">
											<li><a onclick="markMessageAsRead();"><spring:message
														code="admin.message.mark.as.read" /></a></li>
											<li><a onclick="markMessageAsUnRead();"><spring:message
														code="admin.message.mark.as.not.read" /></a></li>
											<!-- <li class="divider"></li>
											<li><a href="#">Move to junk</a></li> -->
											<li class="divider"></li>
											<li><a onclick="deleteMessages();"><spring:message
														code="admin.message.delete" /></a></li>
										</ul>
									</div>

								</div>
								<!-- <div class="col-sm-6 search-form">
									<form action="#" class="text-right">
										<div class="input-group">
											<input type="text" class="form-control input-sm"
												placeholder="Lọc thư...">
											<div class="input-group-btn">
												<button type="submit" name="q"
													class="btn btn-sm btn-primary">
													<i class="fa fa-search"></i>
												</button>
											</div>
										</div>
									</form>
								</div> -->
							</div>
							<div class="table-responsive">
								<table class="table table-bordered table-mailbox" id="main-table">
									<thead>
										<tr role="row">
											<th class="small-col"></th>
											<th class="name"><spring:message
													code="admin.message.table.header.from" /></th>
											<th class="subject"><spring:message
													code="admin.message.table.header.subject" /></th>
											<th class="time" ><spring:message
													code="admin.message.table.header.time" /></th>
										</tr>
									</thead>
									<tbody aria-live="polite" aria-relevant="all">
										<c:forEach var="message" items="${messages}">
											<c:choose>
												<c:when test="${message.status }">
													<tr>
												</c:when>
												<c:otherwise>
													<tr class="unread">
												</c:otherwise>
											</c:choose>
											<td class="small-col"><input type="checkbox" name="messageIds" value="${message.id}"/></td>
											<td class="name"><a href="readEmail.html?id=${message.id}&mode=${param.mode}">${message.from }</a></td>
											<td class="subject"><a href="readEmail.html?id=${message.id}&mode=${param.mode}">${message.subject }</a></td>
											<td class="time"><fmt:setLocale
													value="${pageContext.request.locale}" /> <fmt:formatDate
													value="${message.createdDate}" pattern="dd/mm/yyyy hh:mm a" /></td>
											</tr>
										</c:forEach>
									</tbody>
								</table>
							</div>
							<!-- /.row -->
							<%-- <div class="table-responsive">
								<table class="table table-mailbox">
									<c:forEach var="message" items="${messages}">
										<c:choose>
											<c:when test="${message.status }">
												<tr class="unread">
											</c:when>
											<c:otherwise>
												<tr>
											</c:otherwise>
										</c:choose>
										<td class="small-col"><input type="checkbox" /></td>
										<td class="name"><a href="#">${message.from }</a></td>
										<td class="subject"><a href="#">${message.subject }</a></td>
										<td class="time"><fmt:setLocale
												value="${pageContext.request.locale}" /> <fmt:formatDate
												value="${message.createdDate}" pattern="hh:mm a" /></td>
										</tr>
									</c:forEach>
								</table>
							</div> --%>
							<!-- /.table-responsive -->
						</div>
						<!-- /.col (RIGHT) -->
					</div>
					<!-- /.row -->
				</div>
			</div>
			<!-- /.box -->
		</div>
		<!-- /.col (MAIN) -->
	</div>
	<!-- MAILBOX END -->
</section>
<!-- /.content -->
<!-- Page script -->
<script type="text/javascript">
	$(function() {

		"use strict";

		//iCheck for checkbox and radio inputs
		$('input[type="checkbox"]').iCheck({
			checkboxClass : 'icheckbox_minimal-blue',
			radioClass : 'iradio_minimal-blue'
		});

		//When unchecking the checkbox
		$("#check-all").on('ifUnchecked', function(event) {
			//Uncheck all checkboxes
			$("input[type='checkbox']", ".table-mailbox").iCheck("uncheck");
		});
		//When checking the checkbox
		$("#check-all").on('ifChecked', function(event) {
			//Check all checkboxes
			$("input[type='checkbox']", ".table-mailbox").iCheck("check");
		});
		//Handle starring for glyphicon and font awesome
		$(".fa-star, .fa-star-o, .glyphicon-star, .glyphicon-star-empty")
				.click(function(e) {
					e.preventDefault();
					//detect type
					var glyph = $(this).hasClass("glyphicon");
					var fa = $(this).hasClass("fa");

					//Switch states
					if (glyph) {
						$(this).toggleClass("glyphicon-star");
						$(this).toggleClass("glyphicon-star-empty");
					}

					if (fa) {
						$(this).toggleClass("fa-star");
						$(this).toggleClass("fa-star-o");
					}
				});
	});

	var table;
	$(document)
			.ready(
					function() {
						table = $("#main-table")
								.dataTable(
										{
											"aoColumnDefs": [
											                 { 'bSortable': false, 'aTargets': [ 0 ] },
											                 { "bSearchable": false, "aTargets": [ 0,3 ] }
											              ],
											"oLanguage" : {
												"oAria" : {
													"sSortAscending" : '<spring:message javaScriptEscape="true" code="admin.table.page.sSortAscending" />',
													"sSortDescending" : '<spring:message javaScriptEscape="true" code="admin.table.page.sSortDescending" />'
												},
												"oPaginate" : {
													"sFirst" : '<spring:message javaScriptEscape="true" code="admin.table.page.sFirst" />',
													"sLast" : '<spring:message javaScriptEscape="true" code="admin.table.page.sLast" />',
													"sNext" : '<spring:message javaScriptEscape="true" code="admin.table.page.sNext" />',
													"sPrevious" : '<spring:message javaScriptEscape="true" code="admin.table.page.sPrevious" />'
												},
												"sEmptyTable" : '<spring:message javaScriptEscape="true" code="admin.table.page.sEmptyTable" />',
												"sInfo" : '<spring:message javaScriptEscape="true" code="admin.table.page.sInfo" />',
												"sInfoEmpty" : '<spring:message javaScriptEscape="true" code="admin.table.page.sInfoEmpty" />',
												"sInfoFiltered" : '<spring:message javaScriptEscape="true" code="admin.table.page.sInfoFiltered" />',
												"sLengthMenu" : '<spring:message javaScriptEscape="true" code="admin.table.page.sLengthMenu" />',
												"sLoadingRecords" : '<spring:message javaScriptEscape="true" code="admin.table.page.sLoadingRecords" />',
												"sZeroRecords" : '<spring:message javaScriptEscape="true" code="admin.table.page.sZeroRecords" />',
												"sSearch" : '<spring:message javaScriptEscape="true" code="admin.table.page.oLanguage.sSearch" />'
											}
										});
					});
	
	//delete messages
	var jsonString;
	function deleteMessages() {
		var ids = [];
		var idFields = $('input[name="messageIds"]');
		for (var i = 0 ; i < idFields.length ;i++) {
			if (idFields[i].checked) {
				ids.push(idFields[i].value);
			}
		}
		//send request to server
		if (ids.length > 0) {
			jsonString = JSON.stringify(ids);
			$("#warning-dialog").modal('show');
		} else {
			//pop up error message
			$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.message.select.message" />');
			$("#error-dialog").modal('show');
		}
		
		return false;
	}
	
	function confirm() {
		if (jsonString != null) {
			var data = 'mode=${param.mode}&ids='+jsonString;
			$.ajax({
				url : 'deleteMessages.html',
				type : 'POST',
				data : data,
				dataType : 'text',
				//contentType : "application/json; charset=utf-8",
				success : function(response) {
					if (response=='success') {
						var ids = JSON.parse(jsonString);
						for (var i = 0 ; i < ids.length; i++) {
							var row = $('input[name="messageIds"][value='+ids[i]+']').closest('tr').get(0);
							table.fnDeleteRow(table.fnGetPosition(row));
						}
						checkEmailAlert();
					} else {
						$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.error.dialog.body" />');
						$("#error-dialog").modal('show');
					}
					//remove all
					jsonString = null;
				},
				error : function() {
					$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.error.dialog.body" />');
					$("#error-dialog").modal('show');
					//remove all
					jsonString = null;
				}
			});
			
		} else {
			$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.message.select.message" />');
			$("#error-dialog").modal('show');
		}
		
		return false;
	}
	
	function markMessageAsRead() {
		var ids = [];
		var idFields = $('input[name="messageIds"]');
		for (var i = 0 ; i < idFields.length ;i++) {
			if (idFields[i].checked) {
				ids.push(idFields[i].value);
			}
		}
		//send request to server
		if (ids.length > 0) {
			jsonString = JSON.stringify(ids);
			var data = 'ids='+jsonString;
			$.ajax({
				url : 'markMessageAsRead.html',
				type : 'POST',
				data : data,
				dataType : 'text',
				//contentType : "application/json; charset=utf-8",
				success : function(response) {
					if (response=='success') {
						var ids = JSON.parse(jsonString);
						for (var i = 0 ; i < ids.length; i++) {
							var row = $('input[name="messageIds"][value='+ids[i]+']').closest('tr').get(0);
							row.className="";
						}
						checkEmailAlert();
					} else {
						$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.error.dialog.body" />');
						$("#error-dialog").modal('show');
					}
					//remove all
					jsonString = null;
				},
				error : function() {
					$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.error.dialog.body" />');
					$("#error-dialog").modal('show');
					//remove all
					jsonString = null;
				}
			});
		} else {
			//pop up error message
			$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.message.select.message" />');
			$("#error-dialog").modal('show');
		}
		
		return false;
	}
	
	function markMessageAsUnRead() {
		var ids = [];
		var idFields = $('input[name="messageIds"]');
		for (var i = 0 ; i < idFields.length ;i++) {
			if (idFields[i].checked) {
				ids.push(idFields[i].value);
			}
		}
		//send request to server
		if (ids.length > 0) {
			jsonString = JSON.stringify(ids);
			var data = 'ids='+jsonString;
			$.ajax({
				url : 'markMessageAsUnRead.html',
				type : 'POST',
				data : data,
				dataType : 'text',
				//contentType : "application/json; charset=utf-8",
				success : function(response) {
					if (response=='success') {
						var ids = JSON.parse(jsonString);
						for (var i = 0 ; i < ids.length; i++) {
							var row = $('input[name="messageIds"][value='+ids[i]+']').closest('tr').get(0);
							row.className="unread";
						}
						checkEmailAlert();
					} else {
						$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.error.dialog.body" />');
						$("#error-dialog").modal('show');
					}
					//remove all
					jsonString = null;
				},
				error : function() {
					$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.error.dialog.body" />');
					$("#error-dialog").modal('show');
					//remove all
					jsonString = null;
				}
			});
		} else {
			//pop up error message
			$('#error-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.message.select.message" />');
			$("#error-dialog").modal('show');
		}
		
		return false;
	}
</script>